#!/usr/bin/env python

import numpy as np
import pylab as pl
import os.path as osp
import sys
from matplotlib.font_manager import FontProperties as FP

def new_frame(filep):
	line = '1'
	while not line.startswith('[/FRAME]'):
		line = filep.readline()
		if line.startswith('pkt_pos='):
			pos = int(line[line.find('=')+1:])
		if line.startswith('pict_type='):
			pict_type = line[line.find('=')+1:-1]
	return pos, pict_type


if __name__ == '__main__':
	input_filename = sys.argv[1]

	f = open(input_filename,'r')

	pos_type = []

	##### DATA EXTRACTION #####

	line = '1'
	while line:
		line = f.readline()
		if line.startswith('[FRAME]'):
			position, pict_type = new_frame(f)
			pos_type.append((position, pict_type))

	# Determine distribution of |Gop20|

	GOP_size_list=[]
	GOP_20_temp_size=0
	i_ref=0

	for i in range(len(pos_type)-1)	:
	
		if (str(pos_type[i+1][1]).lower()=='i'):
			GOP_20_temp_size=pos_type[i][0]-pos_type[i_ref][0]
			GOP_size_list.append(GOP_20_temp_size)
			i_ref=i

	for i in range(len(GOP_size_list)): 	
		GOP_size_list[i]=GOP_size_list[i]/1024 # Scale to kbytes !!
	
	##### PLOTTINGS #######

	histogram_bin_size = 200
	max_size=1000
	min_size=0

	hist_GOP20_size = pl.histogram(GOP_size_list, histogram_bin_size, (min_size, max_size))

	fp = FP()
	fp.set_size('small')

	fig = pl.figure()
	ax1 = fig.add_subplot(111)
	bar_p = ax1.bar(hist_GOP20_size[1][:-1],hist_GOP20_size[0], width=(max_size-min_size)/histogram_bin_size)

	ax1.set_xlabel('|GOP20| [kBytes]')
	ax1.set_ylabel('GOP count [-]')
	ax1.grid('on')

#	pl.show()

	svndir = osp.abspath('../../rapport/figs')
	pl.savefig(svndir+'/'+'dist_GOP20_size'+'.eps')






